#include "extraClock.h"
#include "rtc.h"
#include "stm32f4xx_hal_rtc.h"
#include <stdbool.h>

Bool validate_DTL(const DTL* en) {
  if(!en)
    return false;
	//NOTE 实际使用未填写周几,周几为0也合法
  if(en->YEAR < 1970 || en->YEAR > 2262 || en->MONTH < 1 || en->MONTH > 12 || en->DAY < 1 || en->DAY > 31 ||
     en->HOUR > 23 || en->MINUTE > 59 || en->SECOND > 59 ) { //|| en->WEEKDAY < 1 || en->WEEKDAY > 7 移除该条件
    return false; // 不合法
  }
  return true; // 合法
} 
Bool WR_SYS_T(Bool en, const DTL* in, Int* ret_val) {
  if(!en || !in || !ret_val)
    return false;
  if(validate_DTL(in) == false) {
    *ret_val = 8081; // 错误代码
    return false;
  }
  RTC_TimeTypeDef time_handle;
  RTC_DateTypeDef date_handle;
  time_handle.Hours   = in->HOUR;
  time_handle.Minutes = in->MINUTE;
  time_handle.Seconds = in->SECOND;

  date_handle.Year    = in->YEAR - 1970; // 年从1970年开始
  date_handle.Month   = in->MONTH;
  date_handle.Date    = in->DAY;
  date_handle.WeekDay = in->WEEKDAY==0?1:in->WEEKDAY; // 星期1~7

  HAL_RTC_SetTime(&g_rtc_handle, &time_handle, RTC_FORMAT_BIN);
  HAL_RTC_SetDate(&g_rtc_handle, &date_handle, RTC_FORMAT_BIN);
  *ret_val = 0; // 成功
  return true;  // 成功
}
Bool RD_SYS_T(Bool en, DTL* out, Int* ret_val) {
  if(!en || !out || !ret_val)
    return false;
  RTC_TimeTypeDef time_handle;
  RTC_DateTypeDef date_handle;
  HAL_RTC_GetTime(&g_rtc_handle, &time_handle, RTC_FORMAT_BIN);
  HAL_RTC_GetDate(&g_rtc_handle, &date_handle, RTC_FORMAT_BIN);
  out->YEAR        = date_handle.Year + 1970; // 年从1970年开始
  out->MONTH       = date_handle.Month;
  out->DAY         = date_handle.Date;
  out->WEEKDAY     = date_handle.WeekDay; // 星期1~7
  out->HOUR        = time_handle.Hours;
  out->MINUTE      = time_handle.Minutes;
  out->SECOND      = time_handle.Seconds;
  out->MILLISECOND = 0; // 毫秒暂时不支持
  *ret_val         = 0; // 成功
  return true;          // 成功
}
